package com.bizzan.bitrade.controller;

import com.rzcode.coinex.kernel.common.response.R;
import com.rzcode.coinex.kernel.service.CoinService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用于检查币种rpc是否正常
 */
@Slf4j
@RestController
@RequestMapping("test")
@RequiredArgsConstructor
public class TestController {
    ;

    private final RestTemplate restTemplate;

    private final CoinService coinService;

    /**
     * 检查指定单位的RPC服务高度。
     *
     * @param unit 单位，如BTC, ETH等
     * @return 包含RPC服务高度的结果消息
     */
    @RequestMapping("/height/{unit}")
    public R checkHeight(@PathVariable("unit") String unit) {
        String serviceName = "SERVICE-RPC-" + unit.toUpperCase();
        String url = "http://" + serviceName + "/rpc/height";
        ResponseEntity<R> response = restTemplate.getForEntity(url, R.class);
        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("Remote call successful: service={}, result={}", serviceName, response.getBody());
            return R.ok(response.getBody());
        } else {
            log.error("Failed to get height for service {}: {}", serviceName, response.getStatusCode());
            return R.fail("Failed to get height for service " + serviceName);
        }
    }

    /**
     * 检查所有支持的币种RPC服务是否正常工作。
     *
     * @return 包含所有RPC服务状态的结果消息
     */
    @RequestMapping("/status")
    public R checkAllRpcStatus() {
        log.info("Checking status of all RPC services");
        List<String> units = coinService.findAllRpcUnit();
        if (units.isEmpty()) {
            return R.fail("No RPC coins found!");
        }
        log.info("Found {} RPC units", units.size());
        Map<String, ResponseEntity<R>> statuses = units.stream().collect(Collectors.toMap(
                unit -> "http://SERVICE-RPC-" + unit.toUpperCase() + "/rpc/height",
                unit -> restTemplate.getForEntity("http://SERVICE-RPC-" + unit.toUpperCase() + "/rpc/height", R.class),
                (existing, replacement) -> existing,
                LinkedHashMap::new
        ));
        log.info("RPC statuses collected: {}", statuses);
        return R.ok(statuses);
    }


}
